/* The MIT License (MIT)

	Copyright (c) 2013 Schpitt <schpitt@gmail.com>
	https://code.google.com/p/updator/

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE. */

#include <string>
#include <sstream>

#include "boost/filesystem.hpp"

#include "sha2.h"
#include "lzma_compression.h"

using namespace boost::filesystem;

const unsigned int SHA256_BUFFER_SIZE  = 14000;

#define LOG(x) do { std::stringstream s; s << x; printf("%s\r\n", s.str().c_str()); } while(0)

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

class Generator
{
	path root_dir;
	path hashfile;

	bool compress_file;
	path compressed_root_dir;

	FILE* file_out;

	public:
		Generator( const std::string& p_root_dir, const std::string& p_compressed_root_dir, const std::string& p_hashfile_path ) 
		{
			root_dir = path(p_root_dir);
			LOG("root dir : " << root_dir.string() );

			compress_file = p_compressed_root_dir.length() > 0;
			if(compress_file) {
				compressed_root_dir = path(p_compressed_root_dir);
				LOG("compressed root dir : " << compressed_root_dir.string() );
			}

			hashfile = path(p_hashfile_path);
		}
		~Generator() { }

		//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

		path skipFirst( const path& p_path )
		{
			path to_return;
			for(auto it = ++p_path.begin(); it != p_path.end(); ++it)
				to_return /= *it;
			return to_return;
		}

		//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

		void getHash( const path& p_file_path, char* p_buffer )
		{
			FILE * file;
			SHA256_CTX	ctx256;

			file = fopen( p_file_path.string().c_str(), "rb" );
			SHA256_Init(&ctx256);
			int l, kl=0;
			char buf[SHA256_BUFFER_SIZE];
			while ((l = fread(buf,1,sizeof(buf),file)) > 0) {
				kl += l;
				SHA256_Update(&ctx256, (unsigned char*)buf, l);
			}
			fclose (file);
			SHA256_End(&ctx256, buf);

			memcpy(p_buffer, buf, 32);
		}

		//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

		void handleFile( const path& p_file_path ) 
		{
			path filename = p_file_path.filename();

			unsigned int current_file_size = 0;

			if(compress_file) {
				// file compression
				path compressed_dir = compressed_root_dir/skipFirst(p_file_path.parent_path());
				path compressed_file = compressed_dir/path(filename.string()+".xz");

				create_directories(compressed_dir);
				compress(p_file_path.string(), compressed_file.string());
				current_file_size = file_size( compressed_file );
			}
			
			char hash[33];
			memset(hash, 0, sizeof(hash));
			getHash( p_file_path, hash );

			std::stringstream ss;
			ss << (compress_file?"Az:":"Ab:")
			   << skipFirst(p_file_path).string()
			   << ":" 
			   << (compress_file?current_file_size:file_size( p_file_path ))
			   << ":"
			   << std::string(hash)
			   << "\r\n";

			fwrite(ss.str().c_str(), 1, ss.str().length(), file_out);

			LOG(ss.str());
		}

		//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

		void exploreFolder( const path& p_path_folder ) 
		{
			LOG("explore " << p_path_folder.string());

			if(!exists(p_path_folder)) {
				LOG(p_path_folder.string() << " directory do not exist");
				return;
			}
			if(!is_directory(p_path_folder)) {
				LOG(p_path_folder.string() << " is not a directory");
				return;
			}

			std::vector<path> v;
			copy(directory_iterator(p_path_folder), directory_iterator(), back_inserter(v));

			for(auto it = v.begin(); it != v.end(); ++it) {
				LOG(*it);
				if(is_directory(*it)) {
					exploreFolder(*it);
				} else if(is_regular_file(*it)) {
					handleFile(*it);
				}
			}
		}

		//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

		void generate()
		{
			file_out = fopen(hashfile.string().c_str(), "wb+");

			exploreFolder(root_dir);

			fflush(file_out);
			fclose(file_out);
		}
};

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

int main(int argc, char *argv[])
{
	if(argc != 4) {
		printf("number args given : %d instead of 3\r\n", argc-1);
		printf("example : amnov_updator_generator_auto.exe *hashfile *input *output\r\n");
		printf("* hashfile : contains hash, size, command type for each file in folder_input\r\n");
		printf("* input : is the path to the folder where the files to treat are\r\n");
		printf("* output : is the path to the folder where the files from input are compressed\r\n");
		
		system("pause");
		return 0;
	}

	std::string hashfile(argv[1]);
	std::string root_dir(argv[2]);
	std::string compressed_dir(argv[3]);

	Generator generator(root_dir, compressed_dir, hashfile);
	generator.generate();
	
    system("pause");
    return 0;
}
